package com.tao.mytestsocket.http.convert;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tao.utilslib.log.LogUtil;
import com.yanzhenjie.andserver.annotation.Converter;
import com.yanzhenjie.andserver.framework.MessageConverter;
import com.yanzhenjie.andserver.framework.body.StringBody;
import com.yanzhenjie.andserver.http.ResponseBody;
import com.yanzhenjie.andserver.util.IOUtils;
import com.yanzhenjie.andserver.util.MediaType;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * reate by tao on{DATE}
 */
@Converter
public class DefaultConvert implements MessageConverter {

    @Override
    public ResponseBody convert(@Nullable @org.jetbrains.annotations.Nullable Object output, @Nullable @org.jetbrains.annotations.Nullable MediaType mediaType) {
        LogUtil.e("数据转换返回 ");
        String str = "";
        if (output instanceof String)
            str = (String) output;
        else
            str = output.toString();
        return new StringBody(str, mediaType);
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public <T> T convert(@NonNull @NotNull InputStream stream, @Nullable @org.jetbrains.annotations.Nullable MediaType mediaType, Type type) throws IOException {
        LogUtil.e("数据转换  ");
        Charset charset = mediaType == null ? null : mediaType.getCharset();
        if (charset == null) {
            return (T) IOUtils.toString(stream);
        }
        return (T) IOUtils.toString(stream, charset);
    }
}
